﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DeHeng_Mes.Dao.PlcDao
{
    public class CodeTraceDao
    {
        /// <summary>
        /// 查询订单号与追溯码是否绑定
        /// </summary>
        /// <param name="orderId">订单号</param>
        /// <param name="traceCode">追溯码</param>
        /// <returns>如果绑定返回 true，否则返回 false</returns>
        public bool IsBanding(string orderId, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在绑定记录
                return db.Queryable<OrderTrace>()
                    .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                    .Any(x => x.OrderId == orderId && x.FictitiousCode == code);
            }
        }

        /// <summary>
        /// 绑定插入工单号与追溯码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool BandingOrderId(string orderId, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var binding = new OrderTrace
                {
                    OrderId = orderId,
                    FictitiousCode = code,
                    IsSave = SystemConstant.dataNotCreate
                };

                // 插入绑定记录
                var result = db.Insertable(binding).AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10)).ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 绑定插入追溯码与附属码
        /// </summary>
        /// <param name="MaterialCode"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool BandingTraceId(string MaterialCode, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var binding = new TraceParts
                {
                    MaterialCode = MaterialCode,
                    TraceId = traceCode
                };

                // 插入绑定记录
                var result = db.Insertable(binding).AS("trace_parts" + HashUtils.GetHashAsInt(traceCode, 10)).ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 检查追溯码与附属码是否绑定
        /// </summary>
        /// <param name="MaterialCode"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool IsBandingTraceId(string MaterialCode, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在绑定记录
                return db.Queryable<TraceParts>()
                    .AS("trace_parts" + HashUtils.GetHashAsInt(traceCode, 10))
                    .Any(x => x.MaterialCode == MaterialCode && x.TraceId == traceCode);
            }
        }

        /// <summary>
        /// 根据总成码、工位号查找是否保存数据
        /// </summary>
        /// <param name="traceCodeName"></param>
        /// <param name="v"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool IsBandBeat(string traceCode, string station)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在满足条件的数据
                return db.Queryable<PartBeat>()
                    .AS("part_beat" + HashUtils.GetHashAsInt(traceCode, 10))
                    .Any(x => x.TraceNo == traceCode && x.Station == station);
            }
        }

        /// <summary>
        /// 插入绑定总成、工位号、节拍
        /// </summary>
        /// <param name="traceCode"></param>
        /// <param name="station"></param>
        /// <param name="v"></param>
        /// <exception cref="NotImplementedException"></exception>
        public bool BandingBeat(string traceCode, string station, string beat, bool operationStatus)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var binding = new PartBeat
                {
                    TraceNo = traceCode,
                    Station = station,
                    Beat = beat,
                    OperationStatus = operationStatus ? SystemConstant.Ok : SystemConstant.illegal
                };

                // 插入绑定记录
                var result = db.Insertable(binding)
                    .AS("part_beat" + HashUtils.GetHashAsInt(traceCode, 10))
                    .ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 根据订单号与Code，更新追溯码信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="codeTrace"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool UpdateTraceCode(string code, string codeTrace, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 执行更新操作
                int rowsAffected = db.Updateable<OrderTrace>()
                    .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                    .SetColumns(x => x.TraceId == codeTrace) // 假设 CodeTrace 是追溯码字段
                    .Where(x => x.OrderId == orderId && x.FictitiousCode == code) // 更新条件
                    .ExecuteCommand();

                // 返回是否有记录被更新
                return rowsAffected > 0;
            }
        }

        /// <summary>
        /// 插入创建时间
        /// </summary>
        /// <param name="createTime"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool InsertCreateTime(DateTime createTime, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var insertTime = new CollectionTime
                {
                    CreateTime = createTime,
                    TraceID = traceCode
                };

                // 插入绑定记录
                var result = db.Insertable(insertTime).ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 判断该追溯码是否已经存在
        /// </summary>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool GetCodeIsSave(string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<CollectionTime>()
                    .Where(x => x.TraceID == traceCode)
                    .Any();
            }
        }

        /// <summary>
        /// 检查数据库是否存在该条数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool IsBandingWorkId(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 插入绑定记录
                return db.Queryable<TraceSmallParts>()
                    .AS("trace_small_parts" + HashUtils.GetHashAsInt(code, 10))
                    .Where(x => x.FictitiousCode == code).Any();
            }
        }

        /// <summary>
        /// 绑定零件码与虚拟零件码
        /// </summary>
        /// <param name="code"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool BandingWorkId(string code, string traceCode)
        {
            var trace = new TraceSmallParts()
            {
                FictitiousCode = code,
                WorkCode = traceCode
            };
            using (var db = SqlSugarConfig.Db)
            {
                // 插入绑定记录
                return db.Insertable(trace).AS("trace_small_parts" + HashUtils.GetHashAsInt(traceCode, 10)).ExecuteCommand() > 0;
            }
        }

        /// <summary>
        /// 查询该条码与工位节拍数据是否存在
        /// </summary>
        /// <param name="code"></param>
        /// <param name="station"></param>
        /// <returns></returns>
        public bool BeatIsSave(string station, string codeTrace)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 插入绑定记录
                return db.Queryable<PartBeat>().AS("part_beat" + HashUtils.GetHashAsInt(codeTrace, 10)).Where(x => x.TraceNo == codeTrace && x.Station == station).Any();
            }
        }

        /// <summary>
        /// 插入工序状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="operation"></param>
        /// <param name="time"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void InsertPadTrace(string orderId, string traceCode, string operation, string time)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var PadData = new PadTraceCode()
                {
                    OrderId = orderId,
                    TraceId = traceCode,
                    Operation = operation,
                    Time = time
                };
                db.Insertable(PadData).ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据条件查询所有符合条件的追溯码
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="orderId"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public List<PadTraceCode> GetCodes(string operation, string orderId, string time)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PadTraceCode>()
                    .Where(x => x.Operation == operation && x.OrderId == orderId && x.Time == time)
                    .Select(x => new PadTraceCode
                    {
                        OrderId = x.OrderId,
                        Operation = x.Operation,
                        TraceId = x.TraceId,
                        Time = x.Time,
                    })
                    .ToList();
            }
        }

        /// <summary>
        /// 删除该订单Ng二维码表所有信息
        /// </summary>
        /// <param name="orderId"></param>
        public void DeleteAllByOrder(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<PadTraceCode>()
                   .Where(x => x.OrderId == orderId)
                   .ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据订单号与批次查询序列号
        /// </summary>
        /// <param name="beach"></param>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public List<CodeCount> GetCount(string batch, string currentShift, string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<CodeCount>()
                         .Where(x => x.OrderId == orderId && x.Batch == batch && x.CurrentShift == currentShift)
                         .ToList();
            }
        }

        /// <summary>
        /// 根据单号与批次更新序列号
        /// </summary>
        /// <param name="beach"></param>
        /// <param name="orderId"></param>
        /// <param name="count"></param>
        public void UpdateCount(string batch, string orderId, string count)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<CodeCount>()
                  .SetColumns(x => x.Count == count)
                  .Where(x => x.OrderId == orderId && x.Batch == batch)
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入序列号
        /// </summary>
        /// <param name="beach"></param>
        /// <param name="orderId"></param>
        /// <param name="count"></param>
        public void InsertCount(string batch, string orderId, string currentShift, string count)
        {
            var codeCount = new CodeCount()
            {
                Batch = batch,
                Count = count,
                OrderId = orderId,
                CreateTime = DateTime.Now,
                CurrentShift = currentShift
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(codeCount)
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据单号删除总成码生成信息的缓存
        /// </summary>
        /// <param name="orderId"></param>
        public void DeleteByOrderId(string orderId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<CodeCount>()
                    .Where(x => x.OrderId == orderId)
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入一条数据至虚拟一级码表
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="codeTrace"></param>
        /// <param name="code"></param>
        public void InsertAllToCacheTable(string orderId, string codeTrace, string code)
        {
            OrderTrace orderTrace = new OrderTrace()
            {
                OrderId = orderId,
                FictitiousCode = code,
                TraceId = codeTrace,
                SaveCount = 0,
                IsSave = SystemConstant.nCreate
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(orderTrace)
                    .AS("order_trace")
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 绑定插入工单号与追溯码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool BandingOrderIdAll(string orderId, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var binding = new OrderTrace
                {
                    OrderId = orderId,
                    FictitiousCode = traceCode,
                    TraceId = traceCode,
                    IsSave = SystemConstant.dataNotCreate
                };

                // 插入绑定记录
                var result = db.Insertable(binding).AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10)).ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 判断是否存在数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool isSave(string orderId, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>().Where(x => x.OrderId == orderId && x.TraceId == traceCode && x.FictitiousCode == traceCode).Any();
            }
        }

        /// <summary>
        /// 判断Ng工序条码是否已经插入
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="operation"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        public bool PadTraceIsSave(string orderId, string traceCode, string operation, string time)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PadTraceCode>()
                         .Where(x => x.OrderId == orderId && x.TraceId == traceCode && x.Operation == operation && x.Time == time)
                         .Any();
            }
        }

        /// <summary>
        /// 单站，查询OrderId、TraceCode、Code是否插入，TraceCode为实际码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool IsBandingOne(string orderId, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在绑定记录
                return db.Queryable<OrderTrace>()
                    .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                    .Any(x => x.OrderId == orderId && x.TraceId == traceCode);
            }
        }

        /// <summary>
        /// 单站，直接插入OrderId、TraceCode、Code，TraceCode为实际码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool BandingOrderId(string orderId, string traceCode, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var binding = new OrderTrace
                {
                    OrderId = orderId,
                    TraceId = traceCode,
                    FictitiousCode = code,
                    IsSave = SystemConstant.dataNotCreate
                };

                // 插入绑定记录
                var result = db.Insertable(binding).AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10)).ExecuteCommand();

                // 检查是否插入成功
                return result > 0; // 如果插入成功，返回 true
            }
        }

        /// <summary>
        /// 检查缓存表是否插入了数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool CacheIsInsert(string orderId, string traceCode, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在绑定记录
                return db.Queryable<OrderTrace>()
                    .AS("order_trace")
                    .Any(x => x.OrderId == orderId && x.TraceId == traceCode && x.FictitiousCode == code);
            }
        }

        /// <summary>
        /// 根据工单号与总成码查找是否存在数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool IsBandingOrderIdAndCode(string orderId, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<OrderTrace>()
                    .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                    .Any(x => x.OrderId == orderId && x.TraceId == traceCode);
            }
        }

        public void BandingOrderIdAndCode(string orderId, string traceCode)
        {
            var orderTrace = new OrderTrace()
            {
                OrderId = orderId,
                TraceId = traceCode,
                IsSave = SystemConstant.dataNotCreate
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(orderTrace)
                  .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 缓存表是否插入
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <returns></returns>
        public bool CacheIsInsert(string orderId, string traceCode)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询是否存在绑定记录
                return db.Queryable<OrderTrace>()
                    .AS("order_trace")
                    .Any(x => x.OrderId == orderId && x.TraceId == traceCode);
            }
        }

        /// <summary>
        /// 插入缓存表数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        internal void InsertAllToCacheTable(string orderId, string traceCode)
        {
            OrderTrace orderTrace = new OrderTrace()
            {
                OrderId = orderId,
                TraceId = traceCode,
                IsSave = SystemConstant.nCreate
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(orderTrace)
                    .AS("order_trace")
                    .ExecuteCommand();
            }
        }

        /// <summary>
        /// 根据TraceCode与TraceCode2来查找是否存在数据
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="traceCode2"></param>
        /// <returns>返回存在的TraceCode或者TraceCode2字符串</returns>
        public string SmallTraceCodeIsSave(string orderId, string traceCode, string traceCode2)
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询符合条件的记录
                var result = db.Queryable<OrderTrace>()
                    .AS("order_trace" + HashUtils.GetHashAsInt(orderId, 10))
                    .Where(x => x.OrderId == orderId && (x.TraceId == traceCode || x.TraceId == traceCode2))
                    .First();

                // 如果找到结果，返回对应的TraceCode
                if (result != null)
                {
                    // 根据查询到的 TraceId 返回对应的 TraceCode
                    return result.TraceId.Equals(traceCode) ? traceCode : traceCode2;
                }

                // 如果没有找到匹配的数据，返回空字符串或其他合适的值
                return string.Empty;
            }
        }

        /// <summary>
        /// 根据追溯码与零件码去查询数据是否存在
        /// </summary>
        /// <param name="traceCode"></param>
        /// <param name="traceCode2"></param>
        /// <returns></returns>
        public bool SubsidiaryCodeIsBinding(string traceCode, string traceCode2)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceParts>()
                         .AS("trace_parts" + HashUtils.GetHashAsInt(traceCode, 10))
                         .Any(x => x.TraceId == traceCode && x.MaterialCode == traceCode2);
            }
        }

        /// <summary>
        /// 绑定追溯码与零件码
        /// </summary>
        /// <param name="traceCode"></param>
        /// <param name="traceCode2"></param>
        public void SubsidiaryCodeBinding(string traceCode, string traceCode2)
        {
            var traceParts = new TraceParts()
            {
                TraceId = traceCode,
                MaterialCode = traceCode2
            };

            using (var db = SqlSugarConfig.Db)
            {
                db.Insertable(traceParts)
                  .AS("trace_parts" + HashUtils.GetHashAsInt(traceCode, 10))
                  .ExecuteCommand();
            }
        }

        /// <summary>
        /// 判断二维码是否存在
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool GetCodeIsSaveFromPlc(KeyValuePair<string, object> code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                for (int i = 0; i <= 9; i++)
                {
                    bool haveCode = db.Queryable<TraceSmallParts>()
                                      .AS("trace_small_parts" + i)
                                      .Any(x => x.WorkCode == code.Value.ToString());
                    if (haveCode)
                        return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 判断数据是否存在数据库
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="traceCode"></param>
        /// <param name="operation"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public bool PadCodeIsSave(string orderId, string traceCode, string operation, string time)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<PadTraceCode>()
                    .Any(x => x.OrderId == orderId && x.TraceId == traceCode && x.Operation == operation && x.Time == time);
            }
        }

        /// <summary>
        /// 将视觉码与追溯码插入数据库
        /// </summary>
        /// <param name="visionCode"></param>
        /// <param name="traceCode"></param>
        public bool BandingVisionCode(string visionCode, string traceCode)
        {
            var visionCodeTable = new VisionCodeTable()
            {
                TraceId = traceCode,
                VisionId = visionCode
            };

            using (var db = SqlSugarConfig.Db)
            {
                int v = db.Insertable(visionCodeTable)
                          .ExecuteCommand();
                return v > 0 ? true : false;
            }
        }


        /// <summary>
        /// 插入批次码
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="batchCode"></param>
        /// <param name="createTime"></param>
        public bool InsertBatchCode(string orderId, string batchCode, string createTime)
        {
            var traceBatch = new TraceBatch()
            {
                OrderId = orderId,
                BatchId = batchCode,
                CreateTime = createTime
            };

            using (var db = SqlSugarConfig.Db)
            {
                int v = db.Insertable(traceBatch)
                          .AS("order_trace_batch" + HashUtils.GetHashAsInt(batchCode, 10))
                          .ExecuteCommand();

                return v > 0;
            }
        }

        /// <summary>
        /// 绑定批次件节拍、工序、状态、时间
        /// </summary>
        /// <param name="batchCode"></param>
        /// <param name="operation"></param>
        /// <param name="beat"></param>
        /// <param name="operationStatus"></param>
        /// <returns></returns>
        public bool BatchBandingBeat(string batchCode, string operation, string beat, bool operationStatus, string createTime)
        {
            var partBatchBeat = new PartBeatBatch()
            {
                BatchId = batchCode,
                Beat = beat,
                Status = operationStatus ? "1" : "0",
                CreateTime = createTime
            };

            using (var db = SqlSugarConfig.Db)
            {
                int v = db.Insertable(partBatchBeat)
                          .AS("part_beat_batch" + HashUtils.GetHashAsInt(batchCode, 10))
                          .ExecuteCommand();

                return v > 0;
            }
        }
    }
}
